package com.example.springmvcdemo1.controller;

import com.example.springmvcdemo1.entity.UserInfo;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UserController {
   /* @RequestMapping("/hello")*///支持单层路由
    //RequestMapping支持POST,GET,DELETE等
    //和多层路由
    /*@RequestMapping("/mvc/sayHello")*/

    //我们也可以指定好选用Post还是其他的,指定好之后就不可以用其他的了
    @RequestMapping(value = "/hello",method = RequestMethod.POST)
    public String sayHi() {
        return "Hello,SpringMVC";
    }

    @PostMapping("/hi")//这个只支持Post方式
    public String sayHello() {
        return "Hello PostMapping";
    }

    @GetMapping("/sayHi")//只支持GetMapping
    public String sayHi1() {
        return "Hello GetMapping";
    }


    //获取单个参数（参数传递不要使用基础数据类型，会报错）
    //SpringMVC中都存在Request,和response（内置）
    @RequestMapping("/study")
    public String study(String name) {
        return "hello," + name;
    }

    @RequestMapping("/study1")
    public String study1(String name, String password) {
        return "name:" + name + ",password:" + password;
    }


    /*
    * 获取对象
    * */
    @RequestMapping("/reg")
    public Object reg(UserInfo userInfo) {//框架会执行自动的参数映射
        System.out.println(userInfo);
        return userInfo;
    }
    @RequestMapping("/reg1")
    public Object reg1(@RequestBody UserInfo userInfo) {//接收json对象
        System.out.println("UserInfo:" + userInfo);
        return userInfo;
    }

    /*
    * 从path中获取参数
    * */
    @RequestMapping("/reg4/{name}/{password}")
    public Object reg4(@PathVariable String name, @PathVariable String password) {
        return "name:" + name + ",password:" + password;
    }



    /*
    * 上传文件
    * */
/*    @RequestMapping("/myUpload")
    public Object upload(@RequestPart("myimg")MultipartFile file) {
        File file1 = new File("E:\\study\\myimg.jpg");//这样会进行覆盖，因为存储的每次名字都一样
        try {
            file.transferTo(file1);
            return true;
        }catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }*/
    @RequestMapping("/upload")
    public Object upload(@RequestPart("img")MultipartFile file) {
        //UUID生成的随机数更不容易重复
        String fileName = UUID.randomUUID() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));//生成独一无二的文件名
        File file1 = new File("E:\\study\\" + fileName);
        try {
            file.transferTo(file1);
            return true;
        }catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

}
